//
//  RYYuShengzhangViewController.swift
//  SheYangBigData
//
//  Created by 宋海胜 on 2021/1/12.
//  Copyright © 2021 叁拾叁. All rights reserved.
//


import UIKit
import MJRefresh
import RxSwift
import RxDataSources
import Then

class RYYuShengzhangViewController: SYBaseTableViewController, UITableViewDelegate {
    
    var id: Int!
    
    var head = RYYuShengzhangHead()
    
    
    var bgView: EScrollPageItemBaseView = EScrollPageItemBaseView(pageTitle: "生长监测")
    var model: RYProductDetailModel = RYProductDetailModel() {
        didSet {
            self.setupViewModel()
        }
    }
    
    fileprivate var vm: VGTableViewPageViewModel<Sensors>!
    
    
    public var loboVC: RYYuViewController!
    
    public var canScroll: Bool = true {
        didSet {
            self.tableView.isScrollEnabled = canScroll
        }
    }

    
    init(id: Int) {
        super.init(nibName: nil, bundle: nil)
        self.id = id
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setTableView()
        setNoDataView()
        
        
    }
    
    fileprivate func setupViewModel() {
        vm = VGTableViewPageViewModel<Sensors>()
        vm.tableView = tableView
        vm.emptyViewParams = ("", "", 40.0, 30.0)
        tableView.vg_pageProtocol = vm
        let id = "\(model.deviceId ?? "")/\(model.type ?? 0)"
//        vm.getList(type: .nongchangProductJiance(id: "201216000002/2"))
        vm.loadDataClosure = {[weak self] success in
            if let `self` = self {
                if success {
                    self.loadDataSuccessed()
                }
            }
        }
        self.getDetailData(id: id) { (model) in
            
        }
    }
    
    func getDetailData(id : String, success:@escaping (RYProductJianceModel)->()) {
        requestVM.baseRequest(disposeBag: dispose, type: .nongchangProductJiance(id: id), modelClass: SGBaseModel<RYProductJianceModel>.self) {[weak self] (res) in
            if let `self` = self {
                let model:RYProductJianceModel = res.data ?? RYProductJianceModel()
                self.vm.dataSource = []
                var m = Sensors()
                m.deviceName = "传感器"
                m.currentValue = "数值"
                m.range = "参考范围"

                self.vm.dataSource = model.sensors ?? []
                self.vm.dataSource.insert(m, at: 0)
                var headHeight:CGFloat = 0.0
                if model.sensors?.count ?? 0 <= 3 {
                    headHeight = 140.autoWidth()
                } else {
                    headHeight = 240.autoWidth()
                }
                self.head.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height:headHeight)
                self.head.configureView(model.sensors ?? [])
                self.loadDataSuccessed()
                
                success(model)
            }
            
        } Error: {
            
        }
        
    }
    
    func loadDataSuccessed() {
        DispatchQueue.main.async {

            self.setDataSource()
        }
    }
    
    func setTableView() {
        
        //创建表格视图
        self.tableView = UITableView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-BOTTOM_SAFE_HEIGHT - 41.autoWidth() - STATUSBAR_HEIGHT), style:.plain)
        self.tableView.separatorStyle = .none
        self.tableView.backgroundColor = Constant.bgViewColor
        self.tableView!.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        self.view.addSubview(self.bgView)
        self.bgView.addSubview(self.tableView!)
        self.tableView.delegate = self
        self.tableView.bounces = false

        tableView.rx.itemSelected
            .subscribe(onNext:{ [weak self] indexPath in
                if let `self` = self {
                    
                }
            })
            .disposed(by:dispose)
    }
    
    func setNoDataView() {
        noDataView = SYNoDataView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-NAV_HEIGHT))
        noDataView.isHidden = true
        tableView.addSubview(noDataView)
    }
    
    func setDataSource() {
        //初始化数据
        let sections = Observable.just([
            SensorsSection(header: "", items: self.vm.dataSource)
        ])
        
        //创建数据源
        let dataSource = RxTableViewSectionedAnimatedDataSource<SensorsSection>(
            //设置单元格
            configureCell: { ds, tv, ip, item in
                let cell: RYYuShengzhangCell = tv.dequeueReusableCell(withIdentifier: "Cell")
                    as? RYYuShengzhangCell ?? RYYuShengzhangCell(style: .default, reuseIdentifier: "Cell")
                cell.selectionStyle = .none
                if ip.row % 2 == 0 {
                    if ip.row == 0 {
                        cell.bgView.backgroundColor = UIColor(hex: 0xCFDFFC)
                    } else {
                        cell.bgView.backgroundColor = UIColor(hex: 0xEBF2FE)
                    }
                
                } else {
                    cell.bgView.backgroundColor = .white
                }
                if ip.row == self.vm.dataSource.count - 1 {
                    cell.bottomV.isHidden = false
                } else {
                    cell.bottomV.isHidden = true
                }
                cell.configure(item)
                return cell
                    
               
                

        },
            //设置分区头标题
            titleForHeaderInSection: { ds, index in
                return ds.sectionModels[index].header
        })
        tableView.dataSource = nil
        //绑定单元格数据
        sections
            .bind(to: tableView.rx.items(dataSource: dataSource))
            .disposed(by: dispose)
        
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        return head
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return self.head.frame.size.height
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let v = UIView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 10.autoWidth()))
        v.backgroundColor = .white
        return v
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10.autoWidth()
    }
}

//自定义Section
struct SensorsSection {
    var header: String
    var items: [Item]
}

extension SensorsSection : AnimatableSectionModelType {
    typealias Item = Sensors

    var identity: String {
        return header
    }

    init(original: SensorsSection, items: [Item]) {
        self = original
        self.items = items
    }
}

extension Sensors: IdentifiableType {
    var identity: String {
        return id!
    }

    typealias Identity = String
}
